package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisIdWorker;
//import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private SimpleRedisLock simpleRedisLock;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private IVoucherOrderService proxy;

//    @Autowired
//    private RedissonClient redissonClient;

    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private static final DefaultRedisScript<Long> SECKKILL_SCRIPT;
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //获取消息队列的消息进行处理
    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";

        @Override
        public void run() {
            //不断从队列中取出任务
            while (true) {
                //获取队列中的订单信息
                try {
                    //获取订单信息
                    //xreadgroup group g1 c1 count 1 block 2000 streams stream.orders >
                    //2秒读不到就返回null
                    List<MapRecord<String, Object, Object>> list = redisTemplate.opsForStream()
                            .read(Consumer.from("g1", "c1"),
                                    StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                                    StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    //判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        //获取失败就继续获取
                        continue;
                    }
                    //解析消息中的订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    //获取成功就创建订单
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //ack确认
                    redisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    //取pendinglist中的消息(消费但是未确认)
                    handlePendingList();

                }
            }
        }

        private void handlePendingList() {
            //取pendinglist中的消息(消费但是未确认)
            while (true) {
                //获取队列中的订单信息
                try {
                    //获取订单信息
                    //xreadgroup group g1 c1 count 1  streams streams.order 0
                    //2秒读不到就返回null
                    List<MapRecord<String, Object, Object>> list = redisTemplate.opsForStream()
                            .read(Consumer.from("g1", "c1"),
                                    StreamReadOptions.empty().count(1),
                                    StreamOffset.create(queueName, ReadOffset.from("0")));
                    //判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        //获取失败就继续获取
                        break;
                    }
                    //解析消息中的订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    //获取成功就创建订单
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //ack确认
                    redisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    //取pendinglist中的消息(消费但是未确认)


                }
            }
        }
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            //不断从队列中取出任务
//            while (true) {
//                //获取队列中的订单信息
//                try {
//                    //获取订单信息
//                    VoucherOrder order = orderTasks.take();
//                    //处理订单
//                    handleVoucherOrder(order);
//                } catch (InterruptedException e) {
//                    log.info("处理订单异常");
//                }
//            }
//        }

        /**
         * 处理订单
         */
        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            //获取用户
            Long userId = voucherOrder.getUserId();

//        synchronized (userId.toString().intern()) {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }
            //创建锁对象获取锁
            simpleRedisLock.setName("order:" + userId);
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        boolean isLock = lock.isLocked();

            boolean isLock = simpleRedisLock.tryLock(5);
            if (!isLock) {
                log.error("不允许下单");
                return;
            }
            try {
                //下单
                proxy.createVoucherOrder(voucherOrder);
            } finally {
                simpleRedisLock.unlock();
            }

        }
    }

    static {
        SECKKILL_SCRIPT = new DefaultRedisScript<>();
        SECKKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //获取订单id
        long orderId = redisIdWorker.nextId("order");
        //执行lua脚本判断是否为0
        Long result = redisTemplate.execute(SECKKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        //不为0没有购买资格
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        //为0表示有购买资格，把下单信息加入到阻塞队列
        //TODO 下单信息加入阻塞队列
        //创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        long finalOrderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(finalOrderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//        //存入阻塞队列
//        orderTasks.add(voucherOrder);
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //完成下单和库存的扣减
//        //查询优惠卷
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //判断优惠卷的日期
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀尚未开始");
//        }
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已经结束");
//        }
//        //判断库存
//        if (seckillVoucher.getStock() < 1) {
//            return Result.fail("优惠卷库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//
////        synchronized (userId.toString().intern()) {
////            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        }
//        //创建锁对象获取锁
//        simpleRedisLock.setName("order:" + userId);
////        RLock lock = redissonClient.getLock("lock:order:" + userId);
////        boolean isLock = lock.isLocked();
//
//        boolean isLock = simpleRedisLock.tryLock(5);
//        if (!isLock) {
//            return Result.fail("用户已经下过单了限制购买");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            simpleRedisLock.unlock();
//        }
//
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单功能
        Long userId = voucherOrder.getUserId();
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            return;
        }
        //扣减库存
        //加入乐观锁的方案
        boolean success = seckillVoucherService.update()
                .setSql("stock=stock-1").eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0).update();
        if (!success) {
            return;
        }
        //创建订单
        save(voucherOrder);
    }

}
